package cn.liwq.study.demo.netty.lab.mahjong.server.handler;

import cn.liwq.study.demo.netty.lab.mahjong.common.dto.HelloRequest;
import cn.liwq.study.demo.netty.lab.mahjong.common.dto.HelloResponse;
import cn.liwq.study.demo.netty.lab.mahjong.common.enums.MessageManager;
import cn.liwq.study.demo.netty.lab.mahjong.common.protocol.MahjongProtocol;
import cn.liwq.study.demo.netty.lab.mahjong.common.protocol.MahjongProtocolHeader;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @author lweiqiang
 * @date 2021/5/8
 */
@Slf4j
public class MahjongServerHandler extends SimpleChannelInboundHandler<MahjongProtocol> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MahjongProtocol mahjongProtocol)
            throws Exception {
        MahjongProtocolHeader header = mahjongProtocol.getHeader();
        if (header.getCmd() == MessageManager.HELLO_REQUEST.getCmd()) {
            HelloRequest helloRequest = (HelloRequest) mahjongProtocol.getBody();
            log.info("recv msg: {}", helloRequest);
            // 构建反馈
            HelloResponse response = new HelloResponse();
            response.setMessage("hello " + helloRequest.getName());
            MahjongProtocolHeader outHeader = new MahjongProtocolHeader();
            outHeader.setVersion(header.getVersion());
            outHeader.setCmd(MessageManager.HELLO_RESPONSE.getCmd());
            outHeader.setReqId(header.getReqId());
            MahjongProtocol outProtocol = new MahjongProtocol();
            outProtocol.setHeader(outHeader);
            outProtocol.setBody(response);
            // 写出
            ctx.writeAndFlush(outProtocol);
        }
    }
}
